package org.onvivals.app.mqtt.listener;

import cn.hutool.core.convert.Convert;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.core.server.event.IMqttConnectStatusListener;
import org.onvivals.module.iot.entity.IotDevice;
import org.onvivals.module.iot.service.IIotDeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tio.core.ChannelContext;

/**
 * mqtt 连接状态
 */
@Slf4j
@Service
public class MqttConnectStatusListener implements IMqttConnectStatusListener {
    private static final Logger logger = LoggerFactory.getLogger(MqttConnectStatusListener.class);

	@Autowired
	private IIotDeviceService deviceService;


	@Override
	public void online(ChannelContext context, String clientId, String username) {
		log.info("Mqtt clientId:{} username:{} online.", clientId, username);
		//读取clientId
		if (!clientId.startsWith("server")) {
			// 设备端认证
			String[] clientArray = clientId.split("&");
			//设备码
			String deviceNumber = Convert.toStr(clientArray[1]);
			IotDevice iotDevice = deviceService.selectDeviceBySerialNumber(deviceNumber);
			iotDevice.setStatus(3);
			deviceService.updateById(iotDevice);
		}

	}

	@Override
	public void offline(ChannelContext context, String clientId, String username, String reason) {
		log.info("Mqtt clientId:{} username:{} offline reason:{}.", clientId, username, reason);
		//读取clientId
		if (!clientId.startsWith("server")) {
			// 设备端认证
			String[] clientArray = clientId.split("&");
			//设备码
			String deviceNumber = Convert.toStr(clientArray[1]);
			IotDevice iotDevice = deviceService.selectDeviceBySerialNumber(deviceNumber);
			iotDevice.setStatus(4);
			deviceService.updateById(iotDevice);
		}
	}
}
